package sso.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import sso.dao.UserMapper;

import java.util.List;
import java.util.Map;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String ,Object> userMap = userMapper.selectUserByUsername(username);
        if(userMap == null){
            throw new UsernameNotFoundException("user not found");
        }
        List<String> userPer = userMapper.selectUserPermissions((Long) userMap.get("id"));
//        if(!"DAMN4374".equals(username))
//            throw new UsernameNotFoundException("user not found");
//        String encode = bCryptPasswordEncoder.encode("4374");
//        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_jkd");
//        System.out.println(encode);
        List<GrantedAuthority> grantedAuthorities =
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                        userPer.toString());
        User user = new User(username, (String) userMap.get("password"),AuthorityUtils.createAuthorityList(userPer.toArray(new String[]{})));
        System.out.println(userPer.toArray(new String[]{}));
        return user;
    }
}
